#include <iostream>
#include "csv.h"
#include <set>
using namespace std;;
bool verify(csv& originalData, csv& checkData) {
    bool CR = true;
    int stuIdIndex = checkData.getColIndex(1, "学号"); //学号所在列下标
    // --------------- 查重复项目 ---------------
    set<string> checkSet;
    for (int i = 2; i < checkData.getRows(); i++) {  //数据从下标为2的行开始
        auto insertResult = checkSet.insert(checkData.getCell(i, stuIdIndex));
        if (insertResult.second == false) {
            CR = false;
            cout << "第" << (i+1) << "行重复, 重复学号: " << checkData.getCell(i, stuIdIndex) << endl;
        }
    }
    // --------------- 对比originalData ---------------
    for (const string& item : checkSet) { //遍历checkData中所有未重复的学号
        auto checkRow = checkData.getRow(stuIdIndex, item);
        auto originalRow = originalData.getRow(stuIdIndex, item);
        if (checkRow.empty() || originalRow.empty()) continue;
        for (int i = stuIdIndex+1; i < checkRow.size(); i++) {  //从学号所在列的下一列开始对比
            if (checkRow[i] != originalRow[i]) {
                cout << "学号:" << item<<"\n"<< checkData.getCell(1, i) << "错误\n应为："<< originalRow[i] << ",实为：" << checkRow[i] << "" << endl;
                CR = false;
            }
        }
    }
    // --------------- 查缺失项 ---------------
    set<string> originalSet;
    for (int i = 2; i < originalData.getRows(); i++) {  //数据从下标为2的行开始
        originalSet.insert(originalData.getCell(i, stuIdIndex));
    }
    set<string> subSet(originalSet);
    for (const string& item : checkSet) {
        if (subSet.find(item) != subSet.end()) {
            subSet.erase(item);
        }
    }
    if (!subSet.empty()) {
        CR = false;
        cout << "缺少的学号: ";
        for (const auto& item : subSet) {
            cout << item << " ";
        }
        cout << endl;
    }
    return CR;
}
int main () {
    csv originalData("C:\\Users\\Y5L\\CLionProjects\\csv\\original_data.csv");
    csv checkData("C:\\Users\\Y5L\\CLionProjects\\csv\\data_for_check.csv");
    // 解析失败直接退出程序
    if (!(originalData.parse() && checkData.parse())) {
        cout << "parse error" << endl;
        return -1;
    }
    cout << "数据解析完成" << endl;
    if ( verify(originalData, checkData) ) {
        cout << "验证通过" << endl;
    } else {
        cout << "验证失败" << endl;
    }
    return 0;
}